import json
import time
import datetime

# 开启自动执行任务


from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from sensors.bottomfac.bottom import sysTime
from sensors.bottomfac.bottom import tcp
from sensors.common.AutoPlay import openSensor, resetSensorState, closeSensor, resetAllSensorsState, setAutoForFan, \
    setAutoForSquirm, closeAutoForSquirm
from .models import UserInfo, DevInfo
from .models import SystemSitting

from .common.Scheduler import startScheduler
from .common.Scheduler import scheduler
from .common.Scheduler import removeJobByName, scheduler
startScheduler()

def tcpJob():
    # 初始化tcpSever
    try:
        tcp.tcpInit()
        removeJobByName('tcpJob')
        print('-----Sys Init tcp server-----')
    except:
        print('-----Sys Init tcp server err-----')
scheduler.add_job(tcpJob, 'interval', id='tcpJob', seconds=1)  # 定时执行

print("view_Start==================")


# 测试
@csrf_exempt
def test(request):
    # scheduler.add_job(job, 'interval', id='a', seconds=10)
    # a = SystemSitting(type_name='time_calibrated')
    # a.save()
    return JsonResponse({
        "msg": "ok"
    })

# 获取用户信息
@csrf_exempt
def usersInfo(request):
    if request.method == 'GET':
        userList = UserInfo.objects.all()
        myData = []
        for i in userList:
            myData.append({
                'name': i.username,
                'passwd': i.password,
            })
        return JsonResponse({
            'code': 200,
            'data': myData,
        })
    else:
        return JsonResponse({
            'code': 400,
            'msg': '方法不被允许',
        })


# 登录
@csrf_exempt
def login(request):
    if request.method == 'POST':
        # 执行校对数据库中传感器的状态
        # resetAllSensorsState()
        data = json.loads(request.body.decode())
        try:
            userList = UserInfo.objects.get(username=data.get('name'))
        except:
            back = {
                'code': 400,
                'msg': "用户不存在！"
            }
        else:
            if data.get('password') == userList.password:
                back = {
                    'code': 200,
                    'msg': '登录成功！'
                }
            else:
                back = {
                    'code': 400,
                    'msg': "密码错误！"
                }
        return JsonResponse(back)
    else:
        return JsonResponse({
            'code': 401,
            'msg': "方法不允许！"
        })


@csrf_exempt
def setEvents(request):
    if request.method == 'POST':
        msg = json.loads(request.body.decode(), strict=False)
        msg['type'] = 'events'
        try:
            channel_layer = get_channel_layer()
            async_to_sync(channel_layer.group_send)("sensors", {
                "type": "events",
                "message": msg
            })
        except:
            return JsonResponse({
                'code': 400,
                'msg': '推送失败'
            })
        else:
            return JsonResponse({
                'code': 200,
                'msg': '推送成功'
            })
    else:
        return JsonResponse({
            'code': 401,
            'msg': "方法不允许！"
        })


# 根据类型名称获取该类型设备
@csrf_exempt
def getDevInfo(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode())
        try:
            resList = DevInfo.objects.filter(type_name_en=data.get('type'))
            r = []
            for i in resList:
                r.append({
                    'devName': i.dev_name,
                    'times': i.auto_times,
                    'status': i.status,
                    'type': i.type_name_en,
                    'otherSet': i.other_set
                })
            res = {
                'code': 200,
                'r': r
            }
        except:
            res = {
                'code': 401,
                'msg': '没有这种类型'
            }
        else:
            pass
    else:
        res = {
            'code': 401,
            'msg': '方法不允许'
        }
    return JsonResponse(res)


# 根据设备名称设置时间段
@csrf_exempt
def setDevTimes(request):
    if request.method == 'POST':
        from .common.Scheduler import removeJobByName, scheduler
        content = json.loads(request.body.decode())
        times = content.get('times')
        name = content.get('name')
        try:
            targetDev = DevInfo.objects.get(dev_name=name)
        except:
            res = {
                'code': 401,
                'msg': '没有该传感器'
            }
        else:
            try:
                if targetDev.auto_times:
                    delTime = targetDev.auto_times
                    for i in delTime.split(';'):
                        # 关闭当前设备以前设置的任务
                        try:
                            removeJobByName(name)
                        except Exception as e:
                            print(str(e))
                            pass
                # 更新设备信息表中该设备自动开启结束时间
                newList = []
                for i in times:
                    i = str('-'.join(i))
                    newList.append(i)
                targetDev.auto_times = ';'.join(newList)
                targetDev.save()
                # 修正数据库中的设备状态
                resetSensorState(name, times)
            finally:
                # 设置定时器
                for i in times:
                    start_time = i[0].split(':')
                    hour_start = int(start_time[0])
                    minute_start = int(start_time[1])
                    second_start = int(start_time[2])
                    end_time = i[1].split(':')
                    hour_end = int(end_time[0])
                    minute_end = int(end_time[1])
                    second_end = int(end_time[2])
                    scheduler.add_job(openSensor, 'cron',
                                      hour=hour_start,
                                      minute=minute_start,
                                      second=second_start,
                                      id=name + '_' + str(i[0]) + '_open',
                                      args=[name])  # 定时执行
                    scheduler.add_job(closeSensor, 'cron',
                                      hour=hour_end,
                                      minute=minute_end,
                                      second=second_end,
                                      id=name + '_' + str(i[1]) + '_close',
                                      args=[name])  # 定时执行
                res = {
                    'code': 200,
                    'msg': '成功'
                }
    else:
        res = {
            'code': 401,
            'msg': '方法不允许'
        }
    return JsonResponse(res)


# 设置关于有阈值的设备（风扇或者蠕动泵）
@csrf_exempt
def setOtherDev(request):
    if request.method == 'POST':
        content = json.loads(request.body.decode())
        name = content.get('name')
        time = content.get('time')
        threshold = content.get('threshold')
        try:
            targetDev = DevInfo.objects.get(dev_name=name)
        except:
            res = {
                "code": 400,
                "msg": "没有该设备"
            }
        else:
            if len(threshold):
                targetDev.auto_times = str(time)
                newTh = []
                for i in threshold:
                    newI = []
                    for j in i:
                        newI.append(str(j))
                    newTh.append('-'.join(newI))
                targetDev.other_set = ';'.join(newTh)
                targetDev.save()
                res = {
                    'code': 200,
                    'msg': "设置成功"
                }
            else:
                res = {
                    'code': 401,
                    'msg': "请设置阈值"
                }
    else:
        res = {
            'code': 401,
            'msg': '方法不允许'
        }
    return JsonResponse(res)


#: 获取系统时间
@csrf_exempt
def getSysTime(request):
    if request.method == 'POST':
        try:
            returnTime = sysTime.getSysTime()
            #: 返回设置后的时间
            return JsonResponse({
                'code': 200,
                'r': returnTime
            })
        except:
            return JsonResponse({
                'code': 401,
                'msg': "设置失败"
            })


#: 设置系统时间
@csrf_exempt
def setSysTime(request):
    if request.method == 'POST':
        msg = json.loads(request.body.decode(), strict=False)
        try:
            print(msg['time'])
            returnTime = sysTime.setSysTime(msg['time'])
            #: 返回设置后的时间
            return JsonResponse({
                'code': 200,
                'r': returnTime
            })
        except:
            return JsonResponse({
                'code': 401,
                'msg': "设置失败"
            })


#: 设置系统自动获取时间
@csrf_exempt
def setSysAutoTime(request):
    if request.method == 'POST':
        try:
            returnTime = sysTime.autoGetTime()
            #: 返回设置后的时间
            return JsonResponse({
                'code': 200,
                'r': returnTime
            })
        except:
            return JsonResponse({
                'code': 401,
                'msg': "设置失败"
            })


#: 手动开启/关闭设备
# @csrf_exempt
# def manualControlRel(request):
#     if request.method == 'POST':
#         content = json.loads(request.body.decode())
#         name = content.get('name')
#         flag = content.get('flag')
#         targetDev = DevInfo.objects.get(dev_name=name)
#
#         try:
#             if flag:
#                 targetDev.status = 'open'
#                 targetDev.save()
#                 return JsonResponse({
#                     'code': 200,
#                     'msg': '成功'
#                 })
#             if not flag:
#                 targetDev.status = 'close'
#                 targetDev.save()
#                 return JsonResponse({
#                     'code': 200,
#                     'msg': '成功'
#                 })
#             else:
#                 pass
#         except:
#             return JsonResponse({
#                 'code': 401,
#                 'msg': "设置失败"
#             })


# TODO 屏蔽
#: 手动开启/关闭设备
@csrf_exempt
def manualControlRel(request):
    if request.method == 'POST':
        content = json.loads(request.body.decode())
        name = content.get('name')
        flag = content.get('flag')
        print(name, flag)
        targetDev = DevInfo.objects.get(dev_name=name)
        try:
            if flag:
                if tcp.tcpSwitchOpen(name):
                    targetDev.status = 'open'
                    targetDev.save()
                    return JsonResponse({
                        'code': 200,
                        'msg': '成功'
                    })
                else:
                    targetDev.status = 'close'
                    targetDev.save()
                    return JsonResponse({
                        'code': 401,
                        'msg': '设置失败'
                    })
            if not flag:
                if tcp.tcpSwitchClose(name):
                    targetDev.status = 'close'
                    targetDev.save()
                    return JsonResponse({
                        'code': 200,
                        'msg': '成功'
                    })
                else:
                    targetDev.status = 'open'
                    targetDev.save()
                    return JsonResponse({
                        'code': 401,
                        'msg': '设置失败'
                    })
            else:
                pass
        except:
            return JsonResponse({
                'code': 401,
                'msg': "设置失败"
             })


# 手动开始推事件或结束
@csrf_exempt
def pushEvents(request):
    from .common.Scheduler import scheduler, removeJobByName
    status = json.loads(request.body.decode())
    print(status)
    res = {'status': 'ok'}
    if status['status'] == 1:
        try:
            scheduler.add_job(PushEvent,
                              'interval',
                              seconds=10,
                              id='pushEvent')
        except Exception as e:
            res = {
                'status': str(e)
            }
    else:
        try:
            removeJobByName('pushEvent')
        except:
            res = {
                'status': 'err'
            }
    return JsonResponse(res)


# 测试用例
def PushEvent():
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)("sensors", {
        "type": "events",
        "message": {
            'Time': 'C777-67-00 46:46:46',
            'Hum': 25.4,
            'Temp': 25.3,
            'CO2': 1002,
            'Temp2': 24.9,
            'PH': 4.9,
            'ECAline': 1413.0,
            'EC': 314.5,
            'type': 'events'
        }
    })


# 手自动切换
@csrf_exempt
def toggleManual(request):
    if request.method == 'POST':
        try:
            content = json.loads(request.body.decode())
            newStatus = content.get('status')
            target = SystemSitting.objects.get(type_name='manual')
            target.status = newStatus
            resetAllSensorsState()
        except Exception as e:
            res = {
                'code': 401,
                'msg': str(e)
            }
        else:
            target.save()
            if newStatus:
                res = {
                    'code': 200,
                    'msg': "切换成功, 已关闭自动设置"
                }
            else:
                res = {
                    'code': 200,
                    'msg': "切换成功, 开始执行自动设置"
                }
    else:
        res = {
            'code': 400,
            'msg': "方法不允许"
        }
    return JsonResponse(res)


# 查询手自动
@csrf_exempt
def getManualStatus(request):
    if request.method == 'GET':
        content = SystemSitting.objects.get(type_name='manual')
        return JsonResponse({
            "code": 200,
            "r": {
                "status": content.status
            }
        })
    else:
        return JsonResponse({
            "code": 401,
            "msg": "方法不允许"
        })


# 查询是否矫正时间
@csrf_exempt
def isRightTime(request):
    if request.method == 'GET':
        content = SystemSitting.objects.get(type_name='time_calibrated')
        return JsonResponse({
            "code": 200,
            "r": {
                "status": content.status
            }
        })
    else:
        return JsonResponse({
            "code": 401,
            "msg": "方法错误"
        })


# 查询当前时间
@csrf_exempt
def getSystemTime(request):
    if request.method == 'GET':
        now_time = int(time.time())
        return JsonResponse({
            "code": 200,
            "r": {
                "time": now_time
            }
        })
    else:
        return JsonResponse({
            "code": 401,
            "msg": "方法不对"
        })


# scheduler.start()


print("view_end?????????????????????")
